package crawler.sanling;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import dao.AgencyDao;
import util.HttpConnectionGet;
import util.MybatisTool;
import util.TianYanCha;

public class GuangQiSanLingCrawler {
	public List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		String getPro = "http://www.gmmc.com.cn/Ajax/CommonHandler.ashx?method=Province";
		String proText = HttpConnectionGet.getJson(getPro);
		JSONArray proArray = JSON.parseArray(proText);
		for(int i=0;i<proArray.size();i++) {
			String proName = proArray.getJSONObject(i).getString("PROVINCE_NAME");
			String proNum = proArray.getJSONObject(i).getString("PROVINCE_ID");
			long time = new Date().getTime();
			String getCity = "http://www.gmmc.com.cn/Ajax/CommonHandler.ashx?method=City&v="+time+"&ProvinceCode="+proNum;
			String cityText = getDealer(getCity);
			JSONArray cityArray = JSON.parseArray(cityText);
			for(int j=0;j<cityArray.size();j++) {
				String cityName = cityArray.getJSONObject(j).getString("CITY_NAME");
				String cityNum = cityArray.getJSONObject(j).getString("CITY_ID");
				String getDealer = "http://www.gmmc.com.cn/Ajax/CommonHandler.ashx?method=DealerExtendInfo&CityCode="+cityNum+"&Where=&lng=117.02496707&lat=36.68278473";
				String dealerText = getDealer(getDealer);
				JSONArray dealerArray = JSON.parseArray(dealerText);
				if(dealerArray==null || dealerArray.size()<1) {
					continue;
				}
				for(int k=0;k<dealerArray.size();k++) {
					JSONObject dealer = dealerArray.getJSONObject(k);
					String name = dealer.getString("DEALER_SHORTNAME");
					String address = dealer.getString("ADDRESS");
					String sellTell = dealer.getString("SALES_PHONE");
					String serviceTell = dealer.getString("SERVICE_PHONE");
					String typeNum = dealer.getString("DealerType");
					String lat = dealer.getString("LATITUDE");
					String lng = dealer.getString("LONGITUDE");
					List<String> shareholder = TianYanCha.getShareholder(name);
					String sControllingShareholder = shareholder.get(0);
					String sOtherShareholders = shareholder.get(1);
					String type = null;
					if("0".equals(typeNum)){
						type = "4S店";
					} else if ("1".equals(typeNum)) {
						type = "城市展厅";
					} else if ("2".equals(typeNum)) {
						type = "直营店";
					} else {
						type = "服务驿站";
					}
					
					
					AgencyEntity agency = new AgencyEntity();
					agency.setdCloseDate(null);
					agency.setdOpeningDate(null);
					agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
					agency.setnBrandID(-1);
					agency.setsBrand("三菱");

					agency.setnDealerIDWeb(-1);
					agency.setnManufacturerID(-1);
					agency.setsManufacturer("广汽三菱");

					agency.setnState(1);
					agency.setsAddress(address);
					agency.setsCity(cityName);
					agency.setsCustomerServiceCall(serviceTell);
					agency.setsDealerName(name);
					agency.setsDealerType(type);
					agency.setsProvince(proName);
					agency.setsSaleCall(sellTell);
					agency.setsLongitude(lng);
					agency.setsLatitude(lat);
					agency.setsControllingShareholder(sControllingShareholder);
					agency.setsOtherShareholders(sOtherShareholders);
					list.add(agency);
				}
			
			}
			
			
		}
		
		
		
		return list;
	}
	public String getDealer(String path) {
BufferedReader br = null;
		
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			//设置通用属性
			conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			conn.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
			conn.setRequestProperty("Referer", "http://www.gmmc.com.cn/BuyTools/BuyChooses/DealerSearch?tow=");
			conn.connect();//可以省了,使用下面的urlConn.getOutputStream()会自动connect
			//建立输入流,读取返回的信息
			br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null; // 每行内容
			String content = "";
			while ((line = br.readLine()) != null) {
				content += line;
			}
			//System.out.println(content);
			return content;
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		return null;
		
		
		
	}
	public static void main(String[] args) {
		GuangQiSanLingCrawler crawler = new GuangQiSanLingCrawler();
		System.out.println("爬虫开始...");
		AgencyDao dao = new AgencyDao();
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for(AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
	}

}
